package net.pet.commons.helper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import net.pet.dto.admin.AdminUser;


/**
 * Session operation helper.
 * @author guannan.shang
 *
 */
public class SessionHelper {
    private static final String SESSION_ADMIN_USER="admin_user";
    private SessionHelper() {
    }

	public static void setAdminUser(AdminUser adminUser,HttpServletRequest request) {
		setSessionValue(SESSION_ADMIN_USER, adminUser, request);
	}
	public static AdminUser getAdminUser(HttpServletRequest request) {
		return getSessionValue(SESSION_ADMIN_USER,request);
	}
	@SuppressWarnings("unchecked")
	private static <T> T getSessionValue(String propName, HttpServletRequest request) {
        if(request == null) {
            request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        }
        HttpSession session = request.getSession(false);
        if (session == null) {
            return null;
        } else {
            return (T) session.getAttribute(propName);
        }
    }
    
    private static void setSessionValue(String propName, Object value, HttpServletRequest request) {
        if (value == null) {
            return;
        }
        request.getSession().setAttribute(propName, value);
    }
    /**
     * 销毁session
     * @param request
     */
    public static void invalidateSession(HttpServletRequest request) {
        request.getSession().invalidate();
    }
   
}
